package com.huc.tools.tools.mq;

import com.rabbitmq.client.*;
import io.lettuce.core.protocol.ConnectionFacade;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author: 胡成
 * @Version: 0.0.1V
 * @Date: 2018/8/13
 * @Description: 类描述
 **/
public class RabbitmqTools {

    private final static String QUEUE_NAME = "hello2";

    public static void producer() throws IOException, TimeoutException, InterruptedException {

        /* 使用工厂类建立Connection和Channel，并且设置参数 */
        ConnectionFactory factory = new ConnectionFactory();
        // MQ的IP
        factory.setHost("192.168.0.115");
        // MQ端口
        factory.setPort(5672);
        // MQ用户名
        factory.setUsername("guest");
        // MQ密码
        factory.setPassword("guest");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
		/* 创建消息队列，并且发送消息 */
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        String message = "消息2----------";
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println("生产了个'" + message + "'");
		/* 关闭连接 */
        channel.close();
        connection.close();


    }

    public static void cosumer() throws IOException, TimeoutException, InterruptedException {
         /* 建立连接 */
        ConnectionFactory factory = new ConnectionFactory();
        // MQ的IP
        factory.setHost("192.168.0.115");
        // MQ端口
        factory.setPort(5672);
        // MQ用户名
        factory.setUsername("guest");
        // MQ密码
        factory.setPassword("guest");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

		/* 声明要连接的队列 */
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println("等待消息产生：");

		/* 创建消费者对象，用于读取消息 */
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(QUEUE_NAME, true, consumer);

		/* 读取队列，并且阻塞，即在读到消息之前在这里阻塞，直到等到消息，完成消息的阅读后，继续阻塞循环 */
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            System.out.println("收到消息'" + message + "'");
        }
    }

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        producer();
    }
}
